package com.atguigu.tingshu.user.strategy.impl;

import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.model.user.UserVipService;
import com.atguigu.tingshu.model.user.VipServiceConfig;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.mapper.UserVipServiceMapper;
import com.atguigu.tingshu.user.mapper.VipServiceConfigMapper;
import com.atguigu.tingshu.user.strategy.ItemTypeStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.LocalDateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * projectName: com.atguigu.tingshu.user.strategy.impl
 *
 * @author: 吴振鹏
 * description:
 * time: 2025/9/16 17:18
 */
@Slf4j
@Service("1003")
public class VipStrategy implements ItemTypeStrategy {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private VipServiceConfigMapper vipServiceConfigMapper;

    @Autowired
    private UserVipServiceMapper userVipServiceMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void savePaidRecord(UserPaidRecordVo userPaidRecordVo) {
        //  购买vip；user_vip_service - 可能需要续期；
        //  获取到购买时长;vip_service_config.id
        Long vipServiceId = userPaidRecordVo.getItemIdList().get(0);
        VipServiceConfig vipServiceConfig = vipServiceConfigMapper.selectById(vipServiceId);
        // 获取到购买的月份、时长;
        Integer serviceMonth = vipServiceConfig.getServiceMonth();
        //  保存数据：
        UserVipService userVipService = new UserVipService();
        //  赋值：
        userVipService.setOrderNo(userPaidRecordVo.getOrderNo());
        userVipService.setUserId(userPaidRecordVo.getUserId());
        Date currentTime = new Date();
        //开始生效日期
        userVipService.setStartTime(currentTime);

        //  判断当前用户是否是vip并且未过期，续期；
        UserInfo userInfo = userInfoMapper.selectById(userPaidRecordVo.getUserId());
        if (userInfo.getIsVip() == 1 && userInfo.getVipExpireTime().after(currentTime)) {
            // 当前用户是vip且未过期 属于续期； currentTime = 过期时间
            currentTime = userInfo.getVipExpireTime();
        }
        // 获取当前时间（走了if,当前时间会变成未来的过期时间）
        LocalDateTime localDateTime = new LocalDateTime(currentTime);
        //  获取新过期时间 = 当前时间 + 购买的时长
        Date expireTime = localDateTime.plusMonths(serviceMonth).toDate();
        //  设置过期时间
        userVipService.setExpireTime(expireTime);
        //  保存vip购买记录到数据库
        userVipServiceMapper.insert(userVipService);
        //  修改用户的vip标识;
        userInfo.setIsVip(1);
        // 用户信息表有一个字段也涉及vip过期时间，需要修改
        userInfo.setVipExpireTime(expireTime);
        userInfoMapper.updateById(userInfo);
    }
}
